using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using Color=System.Drawing.Color;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Editors
{
	/// <summary>
	/// Provides a System.Drawing.Design.UITypeEditor for visually picking a color.
	/// </summary>
	public class FrameXmlColorEditor : ColorEditor
	{
		/// <summary>
		/// Edits the given object value using the editor style provided by the <see cref="M:System.Drawing.Design.ColorEditor.GetEditStyle(System.ComponentModel.ITypeDescriptorContext)"/> method.
		/// </summary>
		/// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"/> that can be used to gain additional context information.</param>
		/// <param name="provider">An <see cref="T:System.IServiceProvider"/> through which editing services may be obtained.</param>
		/// <param name="value">An instance of the value being edited.</param>
		/// <returns>
		/// The new value of the object. If the value of the object has not changed, this should return the same object it was passed.
		/// </returns>
		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			if (value is Serialization.Color)
			{
				value = ((Serialization.Color) value).ToColor();
			}

			object newValue = base.EditValue(context, provider, value);

			if (newValue != null)
				newValue = Serialization.Color.FromColor((Color) newValue);

			return newValue;
		}

		/// <summary>
		/// Paints a representative value of the given object to the provided canvas.
		/// </summary>
		/// <param name="e">What to paint and where to paint it.</param>
		public override void PaintValue(PaintValueEventArgs e)
		{
			base.PaintValue(e);

			if (e.Value is Serialization.Color)
			{
				var color = (Serialization.Color) e.Value;
				if (color != null)
					using (var brush = new SolidBrush(color.ToColor()))
						e.Graphics.FillRectangle(brush, e.Bounds);
			}
		}
	}
}